<template>
  <div class="app-container">
    <div class="searchform">
      <ToolBar :filters="filters" :getList="getList" :handleAdd="handleCreate"/>
    </div>
    <el-col :span="6" class="customerName" style="padding-bottom: 0px; float:right">
      <span>所属项目：</span>
      {{taskName}}
    </el-col>
    <el-table v-loading="listLoading" :data="projectList" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="95" type="index"></el-table-column>
      <el-table-column label="任务名称" prop="name" align="center"></el-table-column>
      <el-table-column label="任务进度" prop="state" align="center">
          <template slot-scope="scope">
          <el-tag v-if="scope.row.state=== 0 || scope.row.state===32" type="primary">准备</el-tag>
          <el-tag v-else-if="scope.row.state==16" type="primary">验证方案</el-tag>
          <el-tag v-else-if="scope.row.state===8" type="primary">验证过程</el-tag>
          <el-tag v-else-if="scope.row.state===4" type="primary">验证数据</el-tag>
          <el-tag v-else-if="scope.row.state=== 2" type="primary">验证报告</el-tag>
          <el-tag v-else type="primary">验证内容</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="job">
        <template slot-scope="scope">
          <span>{{ scope.row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" prop="projectStatus" align="center" min-width="100" width="150">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.projectStatus=== 1" type="warning">进行中</el-tag>
          <el-tag v-else-if="scope.row.projectStatus=== 2" type="warning">暂停</el-tag>
          <el-tag v-else-if="scope.row.projectStatus=== 3" type="warning">中止</el-tag>
          <el-tag v-else type="primary">已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="工程师" prop="engineerName" align="center"></el-table-column>
      <el-table-column label="操作" fixed="right" width="350" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="handleProgress(scope.$index, scope.row)">进度</el-button>
          <el-button v-if="checkPermission(['manager'])" size="small" type="primary" @click="handleUpdate(scope.$index, scope.row)">
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button v-if="checkPermission(['manager'])" size="small" type="warning" @click="handleUpdatePic(scope.$index, scope.row)">编辑项目图片</el-button>
          <el-button type="danger" size="small" @click="handleTrack(scope.$index, scope.row)">项目跟踪</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--翻页-->
    <Pagination v-show="total>10" :total="total" :pageSize="pagesize" :handleCurrentChange="handleCurrentChange"/>
    <!--编辑界面-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width='950px'>
      <div class="Task">
        <p>主项目信息</p>
        <div class="task_body">
          <el-form label-width="100px" :model="taskForm" :rules="FormRules" ref="taskForm" disabled>
            <el-form-item label="项目名称">
              <el-input v-model="taskForm.name"></el-input>
            </el-form-item>
            <el-form-item label="服务客户">
              <el-input v-model="taskForm.customerName"></el-input>
            </el-form-item>
            <el-form-item label="服务地点">
              <el-input v-model="taskForm.customerAddr"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="taskForm.customerContact"></el-input>
            </el-form-item>
            <el-form-item label="实施计划时间">
              <el-date-picker v-model="taskForm.planStartDate" type="datetime" placeholder="请选择时间"/>
            </el-form-item>
            <el-form-item label="完成时限">
              <el-date-picker v-model="taskForm.planEndDate" type="datetime" placeholder="请选择时间"/>
            </el-form-item>
            <el-form-item label="项目描述">
              <el-input type="textarea" v-model="taskForm.description" :rows="4"></el-input>
            </el-form-item>
            <el-form-item label="项目图片">
              <div class="picList" v-for="item in taskForm.picList">
                <img :src="item.url" v-preview="item.url" preview-nav-enable="true" preview-title-enable="true">
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="button">
        <el-button icon="el-icon-arrow-right" type="primary" circle @click="copyTaskData"></el-button>
      </div>
      <div class="subTask">
        <p>子项目信息</p>
        <div class="task_body">
          <el-form label-width="110px" :model="Form" :rules="FormRules" ref="dataForm">
            <el-form-item label="项目名称" prop="name">
              <el-tooltip class="item" effect="dark" content="项目名称应与数据库内WarehouseName一致" placement="top-end">
                <el-input v-model="Form.name"></el-input>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="服务类型" prop="projectType">
              <el-select v-model="Form.projectType" placeholder="选择服务类型" @change="handleFilter">
                <el-option v-for="item in TaskCategoryOptions" :key="item.projectType" :label="item.projectName" :value="item.projectType"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="服务客户" prop="customerName">
              <el-input v-model="Form.customerName"></el-input>
            </el-form-item>
            <el-form-item label="选择设备" prop="deviceId" v-if="Form.projectType == 2 || Form.projectType == 3 || Form.projectType == 4">
              <el-tooltip class="item" effect="dark" content="需在服务客户下有或新增该设备" placement="top-end">
              <el-select v-model="Form.deviceId" placeholder="选择设备">
                <el-option v-for="item in deviceOptions" :key="item.deviceId" :label="item.deviceName" :value="item.deviceId"></el-option>
              </el-select>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="服务地点" prop="customerAddr">
              <el-input v-model="Form.customerAddr"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="customerContact">
              <el-input v-model="Form.customerContact"></el-input>
            </el-form-item>
            <el-form-item label="实施工程师" prop="engineerId" >
              <el-select v-model="Form.engineerId" placeholder="选择实施工程师">
                <el-option v-for="item in engineerOptions" :key="item.engineerId" :label="item.engineerName" :value="item.engineerId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="实施计划时间" prop="planStartDate">
              <el-date-picker v-model="Form.planStartDate" type="datetime" placeholder="请选择时间" :picker-options="StartOptions"/>
            </el-form-item>
            <el-form-item label="完成时限" prop="planEndDate">
              <el-date-picker v-model="Form.planEndDate" type="datetime" placeholder="请选择时间" :picker-options="EndOptions"/>
            </el-form-item>
            <el-form-item label="项目描述">
              <el-input type="textarea" v-model="Form.description"></el-input>
            </el-form-item>
            <el-form-item label="项目图片" prop="picList" v-if="dialogStatus==='create'">
              <UploadCreateImg
                ref="projectPic"
                :isMultiple="true"
                :FileUrl="FileUrl"
                :Data="Data"
                :picList="Form.picList"
                :handleChange="handleChange"
              ></UploadCreateImg>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 图片编辑弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogPicListVisible" :close-on-click-modal="false">
      <UploadImg
        :picList="picList"
        :FileUrl="FileUrl"
        :Data="Data"
        :handleAvatarSuccess="handleAvatarSuccess"
        :handleRemove="handleRemove"
        :beforeRemove="beforeRemove"
      ></UploadImg>
    </el-dialog>
  </div>
</template>
<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { getTaskCategoryList } from "@/api/taskCategory";
import { getTaskData } from "@/api/task";
import { getEngineerList } from "@/api/users";
import {
  getProjectList,
  getDeviceList,
  createProject,
  updateProject,
  getProjectData,
  deletePic
} from "@/api/project";
import ToolBar from "@/views/layout/components/ToolBar";
import Pagination from "@/views/layout/components/Pagination";
import UploadCreateImg from "@/components/Upload/UploadImg3";
import UploadImg from "@/components/Upload/UploadImg2";
import { isvalidPhone } from "@/utils/validate";
const validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入电话号码"));
  } else if (!isvalidPhone(value)) {
    callback(new Error("请输入正确的11位手机号码"));
  } else {
    callback();
  }
};
export default {
  components: { ToolBar, Pagination, UploadCreateImg, UploadImg },
  data() {
    return {
      taskName: "",
      filters: {
        name: "",
        placeholder: "项目名称"
      },
      id: this.$route.params.id,
      page: 1,
      total: 0,
      pagesize: 10,
      projectList: [],
      Data: {},
      picList: [],
      FileUrl: "/project/pic/insert",
      Data: {},
      TaskCategoryOptions: [],
      engineerOptions: [],
      deviceOptions: [],
      listLoading: false,
      dialogStatus: "",
      textMap: {
        update: "编辑项目",
        create: "新增项目",
        updatePic: "编辑图片"
      },
      dialogPicListVisible: false,
      dialogFormVisible: false,
      taskForm: {},
      Form: {
        name: "",
        projectType: null,
        customerName: "",
        customerAddr: "",
        customerContact: "",
        engineerId: null,
        planStartDate: new Date(),
        planEndDate: new Date(),
        description: "",
        projectStatus: null,
        state: null,
        picList: []
        //tid:null
      },
      FormRules: {
        name: [{ required: true, message: "请填写项目名称", trigger: "blur" }],
        projectType: [
          { required: true, message: "请选择服务类型", trigger: "change" }
        ],
        customerAddr: [
          { required: true, message: "请填写项目服务地址", trigger: "blur" }
        ],
        customerContact: [
          { required: true, trigger: "blur", validator: validPhone }
        ],
        engineerId: [
          { required: true, message: "请选择工程师", trigger: "change" }
        ],
        planStartDate: [
          {
            required: true,
            message: "请填写项目计划开始时间",
            trigger: "change"
          }
        ],
        planEndDate: [
          {
            required: true,
            message: "请填写项目计划完成时限",
            trigger: "change"
          }
        ],
        picList: [
          { required: true, message: "请上传项目图片", trigger: "change" }
        ]
      },
      StartOptions: {
        disabledDate: time => {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      EndOptions: {
        disabledDate: time => {
          if (this.taskForm.planEndDate && this.Form.planStartDate) {
            return time.getTime() > new Date(this.taskForm.planEndDate);
          }
        }
      }
    };
  },
  watch: {
    Form: {
      handler(newval, oldval) {
        this.Form.picList = newval.picList;
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getList();
    this.getTaskCategoryCode();
    this.getTask();
    this.getEngineer();
    
  },
  methods: {
    checkPermission,
    //获取主项目信息
    getTask() {
      getTaskData({ taskId: this.id }).then(response => {
        console.log(response.data)
        this.taskName = response.data.name;
        this.Form.customerName = response.data.customerName;
        this.taskForm = response.data;
      });
    },

    //获取工程师列表
    getEngineer() {
    if(checkPermission(["manager"]) || checkPermission(["admin"]))
    {
        getEngineerList().then(response => {
          this.engineerOptions = response.data.map(item => {
            return { engineerId: item.id, engineerName: item.name };
          });
        });
      }
    },

    //获取项目类别
    getTaskCategoryCode() {
      getTaskCategoryList().then(response => {
        this.TaskCategoryOptions = response.data.map(item => {
          return { projectType: item.id, projectName: item.name };
        });
      });
    },

    getDevice(){
      if (
        this.Form.projectType == 2 ||
        this.Form.projectType == 3 ||
        this.Form.projectType == 4
      ) {
        let data = {
          customerId: this.taskForm.customerId,
          projectType: this.Form.projectType
        };
        getDeviceList(data).then(response => {
          this.deviceOptions = response.data.map(item => {
            return { deviceId: item.id, deviceName: item.name };
          });
        }).catch(e=>{console.log(e)});
      }
    },

    //获取设备列表
    handleFilter() {
      this.getDevice();
    },

    //一键复制主项目信息
    copyTaskData() {
      //this.Form = JSON.parse(JSON.stringify(this.taskForm));
      this.Form.name = this.taskForm.name;
      this.Form.customerName = this.taskForm.customerName;
      this.Form.customerAddr = this.taskForm.customerAddr;
      this.Form.customerContact = this.taskForm.customerContact;
      this.Form.planStartDate = this.taskForm.planStartDate;
      this.Form.planEndDate = this.taskForm.planEndDate;
      this.Form.description = this.taskForm.description;
    },

    // 上传成功后
    handleAvatarSuccess(response, file, fileList) {
      this.$message({
        message: "图片上传成功",
        type: "success"
      });
      this.dialogPicListVisible = false;
      this.getList();
    },

    // 删除图片
    handleRemove(file, fileList) {
      if (file.hasOwnProperty("fid")) {
        deletePic({ fid: file.fid });
      }
    },

    beforeRemove(file, fileList) {
      if (file.hasOwnProperty("originname")) {
        if (fileList.length > 1) {
          return this.$confirm(`确定移除 ${file.originname}？`);
        } else {
          this.$message({
            message: "项目需至少保留一张图片",
            type: "warning"
          });
          return false;
        }
      }
    },

    //图片上传检查
    handleChange(file, fileList) {
      const isImage =
        file.raw.type == "image/png" ||
        file.raw.type == "image/jpg" ||
        file.raw.type == "image/jpeg";
      if (!isImage) {
        this.$message.error("上传图片只能是JPG或者png格式!");
      }

      if (isImage) {
        this.Form.picList = fileList;
      } else {
        fileList.pop();
      }
      return isImage 
    },

    // 翻页
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },

    //获取子项目列表
    getList() {
      this.listLoading = true;
      let data = {
        name: this.filters.name,
        page: this.page,
        size: this.pagesize,
        taskId: this.id
      };
      getProjectList(data).then(response => {
        this.projectList = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },

    //重置表单
    resetForm() {
      this.Form = {
        name: "",
        projectType: null,
        customerName: "",
        customerAddr: "",
        customerContact: "",
        planStartDate: new Date(),
        planEndDate: new Date(),
        description: "",
        projectStatus: null,
        picList: []
      };
    },

    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },

    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.Form.projectStatus = 1;
          let tempData = Object.assign({}, this.Form, { tid: this.id });
          createProject(tempData).then(res => {
            let projectId = res.data.insertId;
            this.Data = { projectId: projectId };
            this.$nextTick(() => {
              this.$refs.projectPic.UploadSubmit();
            });
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "新增项目成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },

    //显示编辑界面
    handleUpdate(index, row) {
      this.Form = Object.assign(this.Form, row);
      this.getDevice()
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },

    //编辑
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.Form);
          updateProject(tempData).then(() => {
            this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },

    //显示图片编辑界面
    handleUpdatePic(index, row) {
      this.picList = [];
      this.dialogStatus = "updatePic";
      this.Data = { projectId: row.pid };
      getProjectData({ projectId: row.pid }).then(response => {
        this.picList = response.data.picList;
        this.dialogPicListVisible = true;
      });
    },
    handleProgress(index, row) {
      this.$router.push({
        path: "/task/project/progress/" + row.pid
      });
    },

    handleTrack(index, row) {
      this.$router.push({
        path: "/task/project/track/" + row.pid
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.dialogWidth {
  width: 950px;
}
.searchform {
  float: left;
}
.customerName {
  font-size: 14px;
  text-align: right;
  span {
    font-weight: 700;
  }
}

.Task,
.subTask {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  display: inline-block;
  vertical-align: middle;
  width: 45%;
  max-height: 100%;
  box-sizing: border-box;
  position: relative;
  p {
    height: 40px;
    line-height: 40px;
    background: #f5f7fa;
    margin: 0;
    padding-left: 15px;
    border-bottom: 1px solid #ebeef5;
    box-sizing: border-box;
    color: #000;
  }
  .task_body {
    height: 760px;
    padding: 10px;
    overflow-y: auto;
  }
}
.button {
  display: inline-block;
  vertical-align: middle;
  padding: 0 15px;
}
.picList {
  img {
    width: 90px;
    float: left;
    margin-right: 5px;
  }
}
.el-form-item {
  margin-bottom: 15px;
}
</style>
  

